package com.mall.common.security;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.mall.common.service.MyCaptchaService;


/**
 * 拦截器 - 后台登录验证码
 */
@Component
public class AdminLoginJCaptchaFilter implements Filter {

	public static final String ADMIN_CAPTCHA_ERROR_URL = "/admin/login.jhtml?error=captcha";// 后台登录验证失败跳转URL
	@Resource private MyCaptchaService myCaptchaService;

	public void init(FilterConfig fConfig) throws ServletException {}

	public void destroy() {}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String captchaId = request.getParameter("captchaId");
		if (StringUtils.isEmpty(captchaId)){
			captchaId = request.getSession().getId();
		}
		boolean isCaptcha = validateCaptcha(request, captchaId);
		if (isCaptcha) {
			chain.doFilter(request, response);
		} else {
			request.getSession().setAttribute("captchaError", true);
			response.sendRedirect(request.getContextPath() + ADMIN_CAPTCHA_ERROR_URL);
		}
	}
	
	/**
	 * 校验验证码.
	 * 
	 * @param request
	 *            HttpServletRequest对象
	 * 
	 */
	protected boolean validateCaptcha(HttpServletRequest request, String captchaId) {
		String captcha = request.getParameter(JCaptchaEngine.CAPTCHA_INPUT_NAME);
		return myCaptchaService.isValid(captchaId, captcha);
	}

}
